<template>
  <view>
    <view class="header">
      <uni-search-bar
        radius="5"
        placeholder="输入关键字搜索"
        v-model="keyword"
        clearButton="auto"
        cancelButton="none"
        @confirm="search"
        @clear="clear"
      ></uni-search-bar>
      <uni-icons color="#0093F5" size="22" type="map" @click="toggleView" />
    </view>

    <!-- 根据 showMap 变量控制显示列表或地图 -->
    <view v-show="!showMap" class="list" style="overflow-y: scroll; height: 90vh">
      <uni-list class="uni-list--waterfall">
        <!-- to 属性携带参数跳转详情页面，当前只为参考 -->
        <uni-list-item
          :border="false"
          class="uni-list-item--waterfall"
          title="景点列表"
          v-for="item in dataList"
          :key="item.id"
          :to="'/pages/detail/detail?id=' + item.id"
        >
          <!-- 通过header插槽定义列表左侧图片 -->
          <template v-slot:header>
            <view class="picture">
              <image :src="item.img" mode="aspectFill"></image>
              <view class="free-num">
                免票：
                <text>{{ item.num }}</text>
                次
              </view>
            </view>
          </template>
          <!-- 通过body插槽定义商品布局 -->
          <template v-slot:body>
            <view class="title uni-ellipsis-1">
              {{ item.name }}
            </view>
            <view class="price-state">
              <text class="price">票价：¥ {{ item.price }}</text>
              <text class="state-1" v-if="item.state == 1">开园中</text>
              <text class="state-0" v-else>已闭园</text>
            </view>
            <view class="open-time">{{ item.storeBeginTime }} - {{ item.storeEndTime }} 开放</view>
            <view class="sign-end-time">签约到期时间：{{ item.endTime }}</view>

            <view class="location">
              <uni-icons type="location" size="14"></uni-icons>
              <text v-show="item.distance">距离({{ item.distance }})</text>
              {{ item.address }}
            </view>
          </template>
        </uni-list-item>
      </uni-list>
    </view>

    <!-- 地图组件 -->
    <view v-show="showMap" class="map-container">
      <!-- 添加 bindmarkertap 事件 -->
      <map
        :latitude="lat"
        :longitude="lng"
        :markers="markers"
        style="width: 100%; height: 90vh"
        bindmarkertap="onMarkerTap"
        bindlabeltap="onLabelTap"
      ></map>
    </view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        dataList: [],
        keyword: '',
        lat: '',
        lng: '',
        showMap: false, // 控制显示列表或地图
        markers: [], // 地图标记
      }
    },
    onLoad() {
      this.getCurrentLocation()
    },
    onPullDownRefresh() {
      this.updateViewSpotData()
      setTimeout(function () {
        uni.stopPullDownRefresh()
      }, 1000)
    },
    onShareAppMessage() {
      return {
        title: '景点列表',
        path: '/pages/index/index',
      }
    },
    onShareTimeline() {
      return {
        title: '景点列表',
        path: '/pages/index/index',
        imageUrl: '',
      }
    },
    methods: {
      search(res) {
        this.keyword = res.value
        this.getDataList()
      },
      clear(res) {
        this.keyword = res.value
        this.getDataList()
      },
      // 获取数据
      async getDataList() {
        const viewspot = uniCloud.importObject('viewspot')
        const res = await viewspot.getViewSpotList(this.keyword, this.lng, this.lat)
        this.dataList = res.data
        this.updateMarkers() // 更新地图标记
      },
      // 获取当前用户定位
      getCurrentLocation() {
        let that = this
        uni.getLocation({
          type: 'gcj02',
          success: function (res) {
            that.lng = res.longitude
            that.lat = res.latitude
            uni.setStorageSync('user_current_point', {
              lng: res.longitude,
              lat: res.latitude,
            })
          },
          fail: function (res) {
            console.log(res)
          },
          complete: function (res) {
            that.getDataList()
          },
        })
      },
      // 更新景点数据
      async updateViewSpotData() {
        const viewspot = uniCloud.importObject('viewspot')
        await viewspot.updateViewSpotData()
        this.getCurrentLocation()
      },
      // 切换显示模式
      toggleView() {
        this.showMap = !this.showMap
      },
      // 更新地图标记
      updateMarkers() {
        this.markers = [
          {
            id: 0,
            latitude: this.lat,
            longitude: this.lng,
            title: '当前位置',
            iconPath: '/static/user-location.png', // 自定义用户位置图标路径
            width: 30,
            height: 30,
            // 显示当前位置标签
            label: {
              content: '当前位置',
              color: '#000000',
              fontSize: 12,
              anchorX: -30, // 水平偏移
              anchorY: -53, // 垂直偏移
              bgColor: '#f3a73f',
              padding: 4,
              borderRadius: 4,
            },
          },
          ...this.dataList.map((item, index) => ({
            id: index + 1,
            latitude: item.lat,
            longitude: item.lng,
            title: item.name,
            iconPath: '/static/map-marker.png', // 自定义景点图标路径
            width: 30,
            height: 30,
            // 显示当前位置标签
            label: {
              content: item.name + (item.distance ? '(' + item.distance + ')' : ''),
              color: '#000000',
              fontSize: 12,
              anchorX: -40, // 水平偏移
              anchorY: -53, // 垂直偏移
              bgColor: '#18bc37',
              padding: 4,
              borderRadius: 4,
            },
          })),
        ]
      },
    },
    // 处理 marker 点击事件
    onMarkerTap(e) {
      const markerId = e.markerId
      // 跳过用户当前位置标记
      if (markerId === 0) {
        return
      }
      const item = this.dataList[markerId - 1]
      if (item && item.id) {
        uni.navigateTo({
          url: `/pages/detail/detail?id=${item.id}`,
        })
      }
    },
    onLabelTap(e) {
      const markerId = e.markerId
      // 跳过用户当前位置标记
      if (markerId === 0) {
        return
      }
      const item = this.dataList[markerId - 1]
      if (item && item.id) {
        uni.navigateTo({
          url: `/pages/detail/detail?id=${item.id}`,
        })
      }
    },
  }
</script>

<style lang="scss">
  page {
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    background-color: #efeff4;
    min-height: 100%;
    height: auto;
  }

  .title {
    display: flex;
    margin-bottom: $uni-spacing-col-base;
    font-size: $uni-font-size-lg;
    color: #3b4144;
    align-items: center;
  }

  .picture {
    width: 100%;
    height: 180px;
    margin-bottom: 10rpx;
    position: relative;

    image {
      width: 100%;
      height: 100%;
      border-radius: 10rpx;
    }

    .free-num {
      position: absolute;
      left: 0;
      bottom: 0;
      background-color: #df6337;
      opacity: 0.9;
      font-size: $uni-font-size-sm;
      color: $uni-text-color-inverse;
      width: 150rpx;
      height: 40rpx;
      line-height: 40rpx;
      text-align: center;

      text {
        font-size: $uni-font-size-lg;
      }
    }
  }

  .uni-ellipsis-1 {
    display: flex;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }

  .price-state {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: $uni-font-size-base;
    margin-bottom: 10rpx;

    .price {
      color: #df6337;
    }

    .state-1 {
      color: $uni-color-success;
      font-weight: bolder;
    }

    .state-0 {
      color: $uni-color-error;
      font-weight: bolder;
    }
  }

  .open-time {
    color: $uni-text-color-grey;
    font-size: $uni-font-size-sm;
    margin-bottom: 10rpx;
  }

  .sign-end-time {
    color: #df6337;
    font-size: $uni-font-size-sm;
    margin-bottom: 10rpx;
  }

  .location {
    color: $uni-text-color-grey;
    font-size: $uni-font-size-sm;
    margin-bottom: 10rpx;
    height: 60rpx;
  }

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 10rpx;

    ::v-deep .uni-searchbar {
      width: 85vw;
    }
  }

  // 默认加入 scoped ，所以外面加一层提升权重
  .list {
    .uni-list--waterfall {
      /* #ifndef H5 || APP-VUE */
      // 小程序 编译后会多一层标签，而其他平台没有，所以需要特殊处理一下
      ::v-deep .uni-list {
        /* #endif */
        display: flex;
        flex-direction: row;
        flex-wrap: wrap;
        padding: 5px;
        box-sizing: border-box;

        /* #ifdef H5 || APP-VUE */
        // h5 和 app-vue 使用深度选择器，因为默认使用了 scoped ，所以样式会无法穿透
        ::v-deep

			/* #endif */
			.uni-list-item--waterfall {
          width: 50%;
          box-sizing: border-box;

          .uni-list-item__container {
            display: flex;
            padding: 5px;
            flex-direction: column;
          }
        }

        /* #ifndef H5 || APP-VUE */
      }

      /* #endif */
    }
  }

  .map-container {
    width: 100%;
    height: 90vh;
  }
</style>
